/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gtugs.web;

import org.gtugs.domain.Chapter;
import org.gtugs.domain.Event;
import org.gtugs.eventsite.GtugsException;
import org.gtugs.eventsite.MeetupEventSite;
import org.gtugs.service.ChapterManager;
import org.gtugs.service.EventManager;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author kevin nilson
 */
public class ImportChaptersEventsController implements Controller {

  private MeetupEventSite meetupEventSite;
  private ChapterManager chapterManager;
  private EventManager eventManager;

  //http://code.google.com/p/json-simple/wiki/DecodingExamples
  public ModelAndView handleRequest(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    List<Event> newEvents = new ArrayList<Event>();
    List<Event> updatedEvents = new ArrayList<Event>();

    List<Chapter> chapters = chapterManager.getActiveChapters();
    for (Chapter chapter : chapters) {
      String meetupGroupId = chapter.getMeetupGroupUrlName();
      if (meetupGroupId != null && !meetupGroupId.trim().equals("")) {
        List<Event> existingEvents =
          eventManager.getEventsForChapter(chapter.getId());
        try {
          List<Event> chapterEvents =
            meetupEventSite.lookupFutureEvents(meetupGroupId);
          for (Event event : chapterEvents) {
            event.setChapterId(chapter.getId());

            Event existingEvent = findExisting(event, existingEvents);
            if (existingEvent == null){
              eventManager.storeEvent(event);
              newEvents.add(event);
            } else{
              //DO NOTHING ON UPDATE
              //existingEvent.setAttendeeCount(event.getAttendeeCount());
              //existingEvent.setCity(event.getCity());
              //existingEvent.setCountry(event.getCountry());
              //existingEvent.setCustomTopic(event.getCustomTopic());
              //existingEvent.setDescription(event.getDescription());
              //existingEvent.setEndDate(event.getEndDate());
              //existingEvent.setEndTime(event.getEndTime());
              //existingEvent.setLatitude(event.getLatitude());
              //existingEvent.setLongitude(event.getLongitude());
              //existingEvent.setName(event.getName());
              //existingEvent.setNotes(event.getNotes());
              //existingEvent.setRoom(event.getRoom());
              //existingEvent.setStartDate(event.getStartDate());
              //existingEvent.setStartTime(event.getStartTime());
              //existingEvent.setState(event.getState());
              //existingEvent.setStreetAddress(event.getStreetAddress());
              //existingEvent.setTimeZone(event.getTimeZone());
              //existingEvent.setUrl(event.getUrl());
              //existingEvent.setZipCode(event.getZipCode());
              //
              //eventManager.storeEvent(existingEvent);
              //updatedEvents.add(existingEvent);
            }
          }
        } catch (GtugsException e) {
          e.printStackTrace();
          // TODO add errors
        }
      }
    }

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("updatedEvents", updatedEvents);
    model.put("newEvents", newEvents);

    return new ModelAndView("imported", "model", model);
  }

  private Event findExisting(Event event, List<Event> existingEvents) {
    if (existingEvents == null) {
      return null;
    }

    for (Event existingEvent : existingEvents) {
      if (existingEvent.getStartDate().getTime() ==
          event.getStartDate().getTime()) {
        return existingEvent;
      }
    }
    return null;
  }

  public void setMeetupEventSite(MeetupEventSite meetupEventSite) {
    this.meetupEventSite = meetupEventSite;
  }

  public void setChapterManager(ChapterManager chapterManager) {
    this.chapterManager = chapterManager;
  }

  public void setEventManager(EventManager eventManager) {
    this.eventManager = eventManager;
  }
}
